package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.KHi18nUtil
import cn.com.kh.getProperty
import cn.com.kh.lark.larkUtils
import com.alibaba.fastjson.JSON
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

public class apiHSTsenddingmseeage implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiHSTsenddingmseeage.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        def outData;
        try {
            //查询配置的url

            List message_urls = eliteBean.chaxun_sql("select DISTINCT message_url from hst_senddingmessage_nodelist where frame_flag = '1'", "dataSource");
            if (message_urls.size() == 0) {
                log.debug("无配置");
                return 1;
            }

            String message_body = "";
            String message_staff = "";
            String message_staff1 = "";
            String message_mobile = "";
            String message_type = "";

            // 飞书通知@人
            String lark_At_Info = "";
            String lark_Send_Text = "";

            boolean beonthejobDeal = false;//是否通知全部人员 默认否

            // 通过系统参数识别使用的语言
            String i18n_Type = KHDBConfig.getParam(eliteBean, "SYSENV", "") == "PRO-ML" ? "en_US" : "zh_CN";
            log.debug("通过系统参数识别使用的语言:" + i18n_Type);

            // 循环取数
            for (int i = 0; i < message_urls.size(); i++) {
                String message_url = message_urls.get(i).get("message_url").toString();
                log.debug("当前待处理的WebHook地址:" + message_url);

                //初始化提示内容
                lark_Send_Text = "";
                //生成guid
                String guid = Util.getGuid();

                // 任务打标
                String updatesql = "update hst_senddingmessage set message_flag = '" + guid + "' where message_url = '" + message_url + "' and message_flag = '0' order by createdate limit 1";
                int updatesqlresult = eliteBean.update(updatesql, "dataSource");

                log.debug("将当前待处理的WebHook地址对应的通知List打上标识,数量:" + updatesqlresult);
                if (updatesqlresult == 1) {

                    //1.先获取 通知类型 与内容信息
                    String selectWaitSQL = '''Select Distinct h.Message_Type As Type,
                                               Concat(\' - ''' + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "工单编号") + '''：\',
                                                      Workorderno, \' \\n - \',
                                                      \'''' + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "工单类型") + '''：\',
                                                      Workordertype, \' \\n - \',
                                                      \'''' + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "工单节点") + '''：\',
                                                      Node_Name, \' \\n - \',
                                                      \'''' + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "创建人") + '''：\',
                                                      s.Staffname, \' \\n - \',
                                                      \'''' + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "创建时间") + '''：\',
                                                      h.Createdate, \' \\n\') As Body
                                          From Hst_Senddingmessage h
                                          Left Join Staff s
                                            On s.Staff_Id = h.Createby
                                         Where 1 = 1
                                           And h.Message_Flag = \'''' + guid + '''\'
                                         Group By h.Workorderno, h.Message_Type, Workordertype, h.Node_Name, s.Staffname, h.Createdate Limit 1''';

                    List message = eliteBean.chaxun_sql(selectWaitSQL, "dataSource");

                    // 获取通知类型
                    message_type = message.get(0).get("Type").toString();
                    // 获取通知内容
                    message_body = message.get(0).get("Body").toString();

                    //2.获取通知人员
                    String selectSQL = '''Select Group_Concat(S1.Mobile Separator ',') Mobile,
                                                   Group_Concat(S1.Staffname Separator ',') Staff1,
                                                   Group_Concat(Case
                                                                  When S1.Mobile Is Null Or S1.Mobile = '' Then
                                                                   Concat('@', S1.Staffname)
                                                                  Else
                                                                   Concat('@', S1.Mobile)
                                                                End Separator ' ') Staff,
                                                   Group_Concat(Distinct Concat('<at user_id="', S1.Staff_Id, '">', S1.Staffname, '</at>')) As Lark_At_Staff
                                              From Hst_Senddingmessage h
                                              Left Join Staff S1
                                                On Find_In_Set(S1.Staff_Id, h.Staffids)
                                             Where 1 = 1
                                               And h.Message_Flag = \'''' + guid + '''\'
                                               And S1.Workstatus = 'ONLINE'
                                             Group By h.Workorderno, h.Message_Type, Workordertype, h.Node_Name, h.Createdate Limit 1''';
                    List Notifypersonnel = eliteBean.chaxun_sql(selectSQL, "dataSource");
                    log.debug("当前钉钉消息通知是否有接收人 接收人结果:" + Notifypersonnel.size());


                    if (Notifypersonnel.size() > 0) {
                        //循环拼接@人名
                        message_staff = Notifypersonnel.get(0).get("Staff").toString();
                        //循环拼接人名
                        message_staff1 = Notifypersonnel.get(0).get("Staff1").toString();
                        //循环拼接手机
                        message_mobile = Notifypersonnel.get(0).get("Mobile").toString();
                        beonthejobDeal = false;

                        // 飞书通知@人员信息
                        lark_At_Info = Notifypersonnel.get(0).get("Lark_At_Staff").toString();

                    } else {//如无接收人，则向上查其主管 按照人管组 人管人处理 获取 在职主管
                        //3.获取通知人员的主管
                        String selectMaSQL = '''Select Group_Concat(S1.Mobile Separator ',') Mobile,
                                                       Group_Concat(S1.Staffname Separator ',') Staff1,
                                                       Group_Concat(Case
                                                                      When S1.Mobile Is Null Or S1.Mobile = '' Then
                                                                       Concat('@', S1.Staffname)
                                                                      Else
                                                                       Concat('@', S1.Mobile)
                                                                    End Separator ' ') Staff,
                                                       Group_Concat(Distinct Concat('<at user_id="', If(S1.Device_Id Is Not Null And S1.Device_Id != '', S1.Device_Id, S1.Staff_Id), '">', S1.Staffname, '</at>')) As Lark_At_Staff
                                                  From (Select Distinct t.Higher As Staffids
                                                          From Authority_Relationship t
                                                          Left Join Rolegroup T1
                                                            On t.Lower = T1.Rolegroup_Id
                                                          Left Join Staffrolegroup Srg
                                                            On Srg.Rolegroup_Id = T1.Rolegroup_Id
                                                          Left Join Hst_Senddingmessage h
                                                            On Find_In_Set(Srg.Staff_Id, h.Staffids)
                                                         Where 1 = 1
                                                           And Message_Flag = \'''' + guid + '''\'
                                                           And t.Higherflag = 1
                                                           And t.Lowerflag = 0
                                                        Union
                                                        Select Distinct t.Higher As Staffids
                                                          From Authority_Relationship t
                                                          Left Join Staff T1
                                                            On t.Lower = T1.Staff_Id
                                                          Left Join Hst_Senddingmessage h
                                                            On Find_In_Set(T1.Staff_Id, h.Staffids)
                                                         Where 1 = 1
                                                           And Message_Flag = \'''' + guid + '''\'
                                                           And t.Higherflag = 1
                                                           And t.Lowerflag = 1) h
                                                  Left Join Staff S1
                                                    On S1.Staff_Id = h.Staffids
                                                 Where 1 = 1
                                                   And S1.Workstatus = 'ONLINE'
                                                 Group By Null Limit 1''';
                        List managerpersonnel = eliteBean.chaxun_sql(selectMaSQL, "dataSource");
                        log.debug("当前钉钉消息通知无接收人则通知其主管:" + managerpersonnel.size());

                        if (managerpersonnel.size() > 0) {
                            //循环拼接@人名
                            message_staff = managerpersonnel.get(0).get("Staff").toString();
                            //循环拼接人名
                            message_staff1 = managerpersonnel.get(0).get("Staff1").toString();
                            //循环拼接手机
                            message_mobile = managerpersonnel.get(0).get("Mobile").toString();
                            beonthejobDeal = false;

                            // 飞书通知@人员信息
                            lark_At_Info = managerpersonnel.get(0).get("Lark_At_Staff").toString();

                        } else {
                            //4.获取通知人员的主管 无在职 则 默认通知全部！！！
                            beonthejobDeal = true;
                            //循环拼接@人名
                            message_staff = "";
                            //循环拼接人名
                            message_staff1 = "";
                            //循环拼接手机
                            message_mobile = "";

                            // 飞书通知@人员信息
                            lark_At_Info = "";
                        }
                    }
                    log.debug("循环拼接@人名 message_@mobile:" + message_staff + " 循环拼接人名 message_name:" + message_staff1 + " 循环拼接手机 message_mobile:" + message_mobile);

                    String[] message_mobile_arr = message_mobile.split(",");

                    int len1 = message_staff1.length();
                    //替换逗号处理人数量字符串长度
                    int len2 = message_staff1.replace(",", "").length();
                    //本次通知人数
                    int len = len1 - len2 + 1;
                    log.debug("本次通知人数:" + len + " 本次是否通知全部人:" + beonthejobDeal);

                    String text = "";

                    // 飞书通知内容拼接
                    // lark_Send_Text = "【📢" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "过河兵工单提醒") + "】\n";
                    String LarkEmoji = getProperty.get("LarkEmoji");
                    LarkEmoji = KHUtil.isNull(LarkEmoji) ? "1" : LarkEmoji;

                    if (message_type == "send") {
                        text = "#### " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "工单提醒");

                        // 飞书通知内容拼接
                        lark_Send_Text = lark_Send_Text + "" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "工单提醒") + (LarkEmoji == "-1" ? "" : "🚩");
                    }else if (message_type == "order") {
                        text = "#### " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "催单提醒");

                        // 飞书通知内容拼接
                        lark_Send_Text = lark_Send_Text + "" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "催单提醒") + (LarkEmoji == "-1" ? "" : "🔔");
                    }

                    log.debug("通知类型：" + text + "飞书通知Title:" + lark_Send_Text);

                    String url = message_url;
                    //body
                    JSONObject bodys = new JSONObject();
                    bodys.put("msgtype", "markdown");
                    JSONObject markdown = new JSONObject();
                    markdown.put("title", "【" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "过河兵工单提醒") + "】");

                    JSONObject at = new JSONObject();
                    at.put("atMobiles", message_mobile_arr);
                    if (len > 6) {
                        //如钉钉同步通知的人员大于6人 则统一艾特全部人
                        at.put("isAtAll", true);
                        text = text + "  \n > " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "本次工单处理人") + " @" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "所有人") + " \n" + message_body;

                        // 飞书通知内容拼接
                        lark_Send_Text = lark_Send_Text + "\n> " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "本次工单处理人") + " <at user_id=\"all\">" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "所有人") + " </at>\n" + message_body;
                    } else if (beonthejobDeal) {
                        //或 通知的人员 与 其主管 都无在职 则统一艾特全部人
                        at.put("isAtAll", true);
                        text = text + "  \n > " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "本次工单处理人") + " @" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "所有人") + " \n" + message_body;

                        // 飞书通知内容拼接
                        lark_Send_Text = lark_Send_Text + "\n> " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "本次工单处理人") + " <at user_id=\"all\">" + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "所有人") + " </at>\n" + message_body;
                    } else {
                        at.put("isAtAll", false);
                        text = text + "  \n > " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "本次工单处理人") + "" + message_staff + " \n" + message_body;

                        // 飞书通知内容拼接
                        lark_Send_Text = lark_Send_Text + "\n> " + KHi18nUtil.getI18n(eliteBean, "DDSEND", i18n_Type, "本次工单处理人") + "" + lark_At_Info + " \n" + message_body;
                    }

                    if (url.indexOf("open.feishu") >= 0) {
                        log.debug("开始调用飞书通知接口...:" + lark_Send_Text);
                        boolean result = sendLarkMsg(eliteBean,url, "", lark_Send_Text,guid,message_url);
                        log.debug("飞书通知接口结果：" + result);

                    } else {
                        // 钉钉通知拼接
                        markdown.put("text", text);
                        bodys.put("markdown", markdown);
                        bodys.put("at", at);

                        log.debug("开始调用钉钉通知接口...:" + JSON.toJSONString(bodys));
                        int timeout = 10000;
                        int enablessLfag = 0;
                        String charset = "utf-8";
                        Map maps = new HashMap();
                        maps.put("Content-Type", "application/json;charset=utf-8");

                        String result = Util.doHttpPostUseHead(url, bodys.toString(), charset, timeout, enablessLfag, maps);
                        log.debug("钉钉通知接口结果：" + result);
                    }

                }

            }

            outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\"}";
        } catch (Exception e) {
            log.error("接口处理异常", e);
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }
        return outData;

    }

    /**
     * @param 消息内容
     * @return boolean
     * @author LiJT
     * @description 飞书自定义机器人消息通知
     * @date 2023-09-27 18:33
     */
    public static boolean sendLarkMsg(EliteBean eliteBean, String WebHookUrl, String WebHookKey, String msg, String guid, String message_url) throws Exception {
        log.debug("调用Lark飞书发送 入参信息-msg:" + msg);

        try {
            //请求的JSON数据
            JSONObject json = new JSONObject();
            json.put("msg_type", "text");
            JSONObject text = new JSONObject();
            text.put("text", msg);
            json.put("content", text);

            // 获取签名
            if (!KHUtil.isNull(WebHookKey)) {
                int timestamp = (int) (System.currentTimeMillis() / 1000);
                log.debug("调用Lark飞书发送 timestamp:" + timestamp);

                String sendSign = larkUtils.GenSign(WebHookKey, timestamp);
                log.debug("调用Lark飞书发送 sendSign:" + sendSign);

                json.put("timestamp", timestamp);
                json.put("sign", sendSign);
            }
            log.debug("调用Lark飞书发送 Body:" + json.toString());

            // 处理头文件
            Map<String, String> headParams = new HashMap<String, String>();
            headParams.put("Content-Type", "application/json;charset=utf-8");

            //发送post请求
            String result = Util.doHttpPostUseHead(WebHookUrl, json.toString(), "UTF-8", 30000, 0, headParams);
            log.debug("调用Lark飞书发送 Result:" + result);

            JSONObject resJson = JSONObject.fromObject(result);

            //任务更新 提交时间 + 接口返回报文
            String updatesql = "update hst_senddingmessage set message_date = now(),msg_parameter='" + resJson.toString() + "' where message_url = '" + message_url + "' and message_flag = '" + guid + "' order by createdate limit 1";
            int updatesqlresult = eliteBean.update(updatesql, "dataSource");

            if (resJson.getInt("StatusCode") == 0) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("调用Lark飞书发送 处理异常", e);
            return false;
        }

    }

}
